package com.sbj.dto.kdn;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sbj.dto.kdn.model.KdnApiModel;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author summer
 * @version 1.0
 * @date 2024/9/14 14:49
 */
public class KdnApiSearch {


    public static String businessId="1863346";

    public static String apikey="5bb2cf1f-fbca-436c-ac2f-38bcc6863610";

    public static String reqURL="https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";

    /**
     * MD5加密
     * str 内容
     * charset 编码方式
     * @throws Exception
     */
    @SuppressWarnings("unused")
    public static String MD5(String str,String charset) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes(charset));
        byte[] result = md.digest();
        StringBuffer sb = new StringBuffer(32);
        for (int i = 0; i < result.length; i++) {
            int val = result[i] & 0xff;
            if (val <= 0xf) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(val));
        }
        return sb.toString().toLowerCase();
    }

    public static void main(String[] args) throws Exception {
        KdnApiModel model = new KdnApiModel();
        model.setLogisticCode("SF0260214976647");
        model.setShipperCode("SF");
        model.setCustomerName("1865");
        JSONObject object = JSON.parseObject(JSON.toJSONString(model));
        object.put("IsReturnRouteMap",1);
        String RequestData= JSON.toJSONString(object);
        Map<String,Object> params = new HashMap<>();
        params.put("RequestData", URLEncoder.encode(RequestData, "UTF-8"));
        params.put("EBusinessID", businessId);
        params.put("RequestType", "8003");
        String dataSign=encrypt(RequestData, apikey, "UTF-8");
        params.put("DataSign",  URLEncoder.encode(dataSign, "UTF-8"));
        params.put("DataType", "2");
        String post = HttpUtil.post(reqURL, params);
        System.out.println(post);
    }
    public static   String encrypt (String content,String keyValue,String charset) throws UnsupportedEncodingException, Exception
    {
        if (keyValue != null)
        {
            return base64(MD5(content + keyValue, charset), charset);
        }
        return base64(MD5(content, charset), charset);
    }

    public static String base64(String str, String charset) throws UnsupportedEncodingException{
       return Base64.encode(str.getBytes(charset));
    }

}
